<script setup>
import * as THREE from "three";
// 导入gltf加载器
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// 导入动画库
import gsap from "gsap";
// 创建场景
const scene = new THREE.Scene();

// 创建相机
const camera = new THREE.PerspectiveCamera(
  75, // 视角
  window.innerWidth / window.innerHeight, // 宽高比
  0.1, // 近平面
  10000 // 远平面
);
camera.position.z = 40;
camera.position.y = 40;

// 创建渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);


const controls = new OrbitControls(camera, renderer.domElement);
// 设置带阻尼的惯性
controls.enableDamping = true;// 设置阻尼系数
controls.dampingFactor = 0.05;

// 添加 环境光

const light = new THREE.AmbientLight(0xffffff, 3)

light.position.set(5,5,5)
scene.add(light)


let mixer = null
let actions = null

// // 实例化加载器gltf
const gltfLoader = new GLTFLoader();



    // 轨道曲线

// 动画循环
var t = 0; // 初始位置
var speed = 0.005; // 移动速度

let carCurve = null
let car = null



// 加载模型
gltfLoader.load(
  // 模型路径
  "./textures/测试小车轨迹.glb",
  // 加载完成回调
  (gltf) => {
    console.log(123, gltf )
    // 渲染物体
    scene.add(gltf.scene);


    gltf.scene.traverse((child) => {
      if (child.name === "立方体") {
        car = child
      }
    
      if (child.name === "NURBS_曲线") {
          // console.log(child);
          const line = child;
          // line.visible = false;
          // 根据点创建曲线
          const points = [];
          for (
            let i = line.geometry.attributes.position.count - 1;
            i >= 0;
            i--
          ) {
            points.push(
              new THREE.Vector3(
                line.geometry.attributes.position.getX(i),
                line.geometry.attributes.position.getY(i),
                line.geometry.attributes.position.getZ(i)
              )
            );
          }

          carCurve = new THREE.CatmullRomCurve3(points);
        }
      })

  }
);







  function handleStart() {
    actions.play()
  }


  function handleStop() {
    if (actions) {
      mixer.stopAllAction()

    }
  }

let clock = new THREE.Clock()

// 渲染循环
function animate() {
  let time = clock.getDelta()
  // Update mixer
  if (mixer) {
    mixer.update(time);
  }
  requestAnimationFrame(animate);
  controls.update()



  // 更新小车在曲线上的位置
  t += speed;
  if (t > 1) {
    t = 0; // 重新开始运动
  }

  if (carCurve ) {
  let position = carCurve.getPoint(t);
    console.log(2222, position)
  // 更新小车的位置和朝向
  car.position.copy(position);
  car.lookAt(carCurve.getPoint(t + 0.01));
}

  renderer.render(scene, camera);
}

animate();

</script>

<template>


  <button @click="handleStart"> 动画执行</button>

  <button @click="handleStop"> 动画停止</button>

</template>
